package com.hxzy.projectssmplus.controller.common;

import com.hxzy.projectssmplus.util.GlobalConst;
import com.hxzy.projectssmplus.vo.AjaxResult;
import com.wf.captcha.ArithmeticCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.Serializable;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 图片验证码
 */
@RestController
public class CaptchaController  {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 算述运算验证码图片
     * @return
     */
    @GetMapping(value = "/common/captchaImage")
    public AjaxResult arithmeticCaptcha(){

        ArithmeticCaptcha arithmeticCaptcha=new ArithmeticCaptcha(150,50,2);
        String text=arithmeticCaptcha.text();
        String base64ImageStr= arithmeticCaptcha.toBase64();

        //uuid  "captcha:"+当成键,  把 text 当做值，写入到redis
        String uuid= UUID.randomUUID().toString();

        //写入redis
        String redisKey= GlobalConst.CAPTCHA_REDIS_PREF+uuid;
        //设定 set(key,value,300,秒)
        this.stringRedisTemplate.opsForValue().set(redisKey,text, GlobalConst.CAPTCHA_REDIS_EXPIRE_SECONDS, TimeUnit.SECONDS );

        //发给前端  图片字符串(base64) ,  uuid发给前端，提交根据uuid查询输入验证码对不对
        AjaxResult ajaxResult = AjaxResult.success();
        ajaxResult.put("imgStr", base64ImageStr);
        ajaxResult.put("uuid", uuid);
        return ajaxResult;
    }

}
